package com.hksj.Intelligentmanagement.exception;


import com.hksj.Intelligentmanagement.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice //aop实现思想
@Slf4j
public class GlobalExceptionHandler {

    //该注解用于捕获所有控制器里面的异常，并进行处理
    @ExceptionHandler(Exception.class)
    public Result failed(Exception e) {
        String msg = "服务器出现未知异常";
        Result exceptionResult = Result.error("服务器出现未知异常");
        //不合法、不正确的参数
        if (e instanceof IllegalArgumentException) {
            msg = e.getMessage();
        }

        //接口异常 前端页面传过来的参数与你controller接收的参数类型不匹配
        if (e instanceof HttpMessageNotReadableException) {
            msg = "请求参数不合规，请校验后重新提交";
        }

        //参数校验异常
        if (e instanceof MethodArgumentNotValidException) {
            msg = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
        }

        if (e instanceof HttpRequestMethodNotSupportedException) {
            msg = "不支持的请求方式";
        }

        if (e instanceof RuntimeException) {
            msg = e.getMessage();
        }
        //String exceptionClassName = e.getClass().getName();
        //exceptionClassName = exceptionClassName.substring(exceptionClassName.lastIndexOf('.') + 1);
        exceptionResult.setMsg(msg);
        return exceptionResult;
    }


    /**
     * 全局捕获security的权限不足异常
     */
    @ExceptionHandler(value = AccessDeniedException.class)
    public Result exceptionHandler(AccessDeniedException e) {
        String s = e.getMessage();
        log.info("权限不足异常！异常处在：[{}] , 原因是：[{}]", s, e.getMessage());
        throw e;
    }

    /**
     * 全局捕获security的认证失败异常
     */
    @ExceptionHandler(value = AuthenticationException.class)
    public Result exceptionHandler(AuthenticationException e) {
        String s = e.getMessage();
        log.info("用户认证失败异常！异常处在：[{}] , 原因是：[{}]", s, e.getMessage());
        throw e;
    }

}

